using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[ExecuteAlways]  // 可选：让 OnValidate 在编辑器里也能生效
[RequireComponent(typeof(RectTransform))]
public class ClickPropagationHandler : MonoBehaviour, IPointerClickHandler
{
    public enum PropagationMode
    {
        [InspectorName("消耗模式")]    Consume,
        [InspectorName("穿透模式")]    PassThrough,
        [InspectorName("穿透触发")]    PenetrateTrigger,
    }

    [Header("模式")]
    public PropagationMode mode = PropagationMode.Consume;

    [Header("点击回调")]
    public UnityEvent onClick;

    // 私有字段
    private CanvasGroup   _canvasGroup;
    private RectTransform _rectTransform;
    private Camera        _uiCamera;

    // 当脚本第一次添加到 GameObject 时调用
    void Reset()
    {
        Setup();
        ApplyMode();
    }

    void Awake()
    {
        Setup();
        ApplyMode();
    }

    void OnEnable()
    {
        Setup();
        ApplyMode();
    }

    // 在 Inspector 中修改时回调
    void OnValidate()
    {
        Setup();
        ApplyMode();
    }

    // 将获取组件的逻辑集中在这里，保证任何时候都能初始化
    private void Setup()
    {
        // RectTransform
        if (_rectTransform == null)
            _rectTransform = GetComponent<RectTransform>();

        // CanvasGroup
        if (_canvasGroup == null)
            _canvasGroup = GetComponent<CanvasGroup>() ?? gameObject.AddComponent<CanvasGroup>();

        // UI 相机（根据父 Canvas 的渲染模式）
        var canvas = GetComponentInParent<Canvas>();
        _uiCamera = (canvas != null && canvas.renderMode != RenderMode.ScreenSpaceOverlay)
                    ? canvas.worldCamera
                    : null;
    }

    // 根据当前 mode 设置 blocksRaycasts
    private void ApplyMode()
    {
        if (_canvasGroup == null) return;  // 防御性编程

        switch (mode)
        {
            case PropagationMode.Consume:
                _canvasGroup.blocksRaycasts = true;
                break;
            case PropagationMode.PassThrough:
            case PropagationMode.PenetrateTrigger:
                _canvasGroup.blocksRaycasts = false;
                break;
        }
    }

    void Update()
    {
        // “穿透触发” 需要手动检测点击位置并触发回调
        if (mode == PropagationMode.PenetrateTrigger)
        {
            #if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBGL
                    if (Input.GetMouseButtonDown(0))
                        TryManualClick(Input.mousePosition);
            #elif UNITY_IOS || UNITY_ANDROID
                    if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began)
                        TryManualClick(Input.touches[0].position);
            #endif
        }
    }

    private void TryManualClick(Vector2 screenPos)
    {
        if (_rectTransform != null &&
            RectTransformUtility.RectangleContainsScreenPoint(_rectTransform, screenPos, _uiCamera))
        {
            onClick.Invoke();
        }
    }

    // Unity 内置的点击事件 —— 只在 blocksRaycasts=true 时才会调用
    public void OnPointerClick(PointerEventData eventData)
    {
        if (mode == PropagationMode.Consume)
            onClick.Invoke();
        // PassThrough: 不处理
        // PenetrateTrigger: blocksRaycasts=false，不会进到这里
    }
}